上面的例子是同步處理響應HTTP請求,GCDWebServer 3.0 起新增了異步處理HTTP請求,方便我們在響應中進行耗時的操作(如網路請求,I/O讀寫操作)。使用時只需將 processBlock 改成 asyncProcessBlock。
import UIKit
import GCDWebServer
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let webServer = GCDWebServer()
webServer.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self, asyncProcessBlock: { (request, completionBlock) in
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5, execute: {
let html = "<html><body>Hello World</body></html>"
let response = GCDWebServerDataResponse(html: html)
completionBlock(response)
})
})
webServer.start(withPort: 8080, bonjourName: "GCD Web Server")
}
}
啟動會訪問網址時會5秒後才顯示網頁。
以下是從"/"到"/index.html"的頁面從定向
import UIKit
import GCDWebServer
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let webServer = GCDWebServer()
webServer.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self, processBlock: { (request) -> GCDWebServerResponse? in
let html = "<html><body>歡迎訪問</body></html>"
return GCDWebServerDataResponse(html: html)
})
webServer.addHandler(forMethod: "GET", path: "/", request: GCDWebServerRequest.self, processBlock: { (request) -> GCDWebServerResponse? in
let url = URL(string: "index.html", relativeTo: request.url)
return GCDWebServerResponse(redirect: url!, permanent: false)
});
webServer.start(withPort: 8080, bonjourName: "GCD Web Server")
print("服务启动成功,使用你的浏览器访问:\(webServer.serverURL!)")
}
}